<?php
/**
 * 设计师服务亮点控制器
 */
namespace Beerus\Modules\Designer\Controllers;

use App\Http\Controllers\Controller;
use Doraemon\model\Designer;
use Doraemon\model\Designer\DesignerSpot;
use Doraemon\model\DesignerFinder\VirtualDialogue;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Widgets\Tab;
use Illuminate\Support\MessageBag;

class ServiceSpotController extends Controller
{

    const PAGE_SIZE = 10;

    const STATUS_POOL = [
        DesignerSpot::STATUS_NORMAL => '开启',
        DesignerSpot::STATUS_DELETE => '关闭'
    ];

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    // 对话列表
    public function index(Request $request, Content $content)
    {
        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);

        $condition = [];
        if (!empty($request['spot_id'])) {
            $condition['spot_id'] = $request['spot_id'];
        }
        if (!empty($request['spot_name'])) {
            $condition['spot_name'] = $request['spot_name'];
        }
        if (!empty($request['spot_status'])) {
            $condition['spot_status'] = $request['spot_status'];
        }

        $total = DesignerSpot::count($condition);
        $condition['ORDER'] = ['spot_id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];
        $lists = DesignerSpot::select('*', $condition);

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => $page_size,
            'keyName' => 'spot_id'
        ]);

        $search_params = http_build_query($condition);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel, $search_params) {
                $grid->setActionClass(DropdownActions::class);
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('spot_id', 'ID')->placeholder('请输入亮点ID');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('spot_name', '亮点名称')->placeholder('请输入亮点名称');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('spot_status', '亮点状态')->select(self::STATUS_POOL);
                    });
                    $filter->expand();
                });

                $grid->column('spot_id', '亮点ID');
                $grid->column('spot_name', '亮点名称');
                $grid->column('spot_status', '亮点状态')->display(function() {
                    return self::STATUS_POOL[$this->spot_status];
                });
                $grid->column('set_num', '已设置人数')->display(function() {
                    return Designer::getNumBySpotId($this->spot_id);
                });
                $grid->column('add_time', '创建时间')->display(function() {
                    return date('Y-m-d H:i:s', $this->add_time);
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->row->setKeyName('spot_id');
                });
            }
        );

        $tab = new Tab();
        $tab->add('服务亮点列表', $gridList->render());
        $content->row($tab);
        return $content
            ->header('服务亮点列表')
            ->description(' ')
            ->breadcrumb(['text' => '服务亮点列表']);
    }

    // 新增/修改奖项信息
    public function edit(Request $request, Content $content, $spot_id = 0) {
        $request = $request->all();

        if (!$spot_id) {
            $is_create = true;
            $header = '新增';
        } else {
            $is_create = false;
            $header = '修改';
        }

        $tab = new Tab();
        $tab->add('服务亮点信息', self::editAction($request, $spot_id, $is_create));
        return $content->header($header)
            ->breadcrumb([
                'text' => '服务亮点',
                'url' => route('spot.list')
            ], ['text' => $header])->row($tab);
    }

    public function editAction($request, $id = 0, $isCreate = false)
    {
        if ($isCreate) {
            $data = [];
            $form = new Form($data);
        } else {
            $data = DesignerSpot::get('*', ['spot_id' => $id]);
            $form = new Form($data);
            $form->text('spot_id', '亮点ID')->setWidth(4, 2)->readOnly();
        }

        $form->text('spot_name', '亮点名称')
            ->setWidth(4, 2)
            ->required()
            ->help('亮点名称请勿超出7个字');
        $form->select('spot_status', '亮点状态')
            ->setWidth(4, 2)
            ->options(self::STATUS_POOL)
            ->default(DesignerSpot::STATUS_DELETE)
            ->help('【关闭】不在客户端展示，【开启】在客户端展示，请谨慎操作');
        $form->confirm('确定提交吗？');
        $form->action('/admin/Designer/service_spot/save');
        return $form->render();
    }

    // 编辑奖项
    public function editSubmit(Request $request)
    {
        $request = $request->all();
        $data = [
            'spot_name' => $request['spot_name'],
            'spot_status' => $request['spot_status']
        ];
        if (mb_strlen($request['spot_name']) > 7) {
            $error = new MessageBag(['title' => '服务亮点字数不能超过7个']);
            return back()->with(compact('error'));
        }
        if (isset($request['spot_id'])) {
            // 如果已经有设计师设置了该亮点，不可修改
            if ($request['spot_status'] && Designer::getNumBySpotId($request['spot_id'])) {
                $error = new MessageBag(['title' => '已有设计师']);
                return back()->with(compact('error'));
            }
            $rs = DesignerSpot::updateInfo($request['spot_id'], $data);
        } else {
            if (DesignerSpot::getByCondition(['spot_name' => $request['spot_name']])) {
                $error = new MessageBag(['title' => '已经存在该亮点']);
                return back()->with(compact('error'));
            }
            $rs = DesignerSpot::create($data);
        }
        $title = isset($request['spot_id']) ? '修改成功' : '添加成功';
        if (!$rs) {
            $error = new MessageBag(['title' => $title]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag(['title' => $title]);
        return redirect('/admin/Designer/service_spot')->with(compact('success'));
    }
}
